package com.jt.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.jt.pojo.User;
import com.jt.pojo.SysResult;
import com.jt.service.DubboUserService;
import com.jt.service.UserService;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import redis.clients.jedis.JedisCluster;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;

/**
 * <p>
 *
 * </p>
 *
 * @author Song
 * @since 2020/11/16
 */
@Controller
@RequestMapping("/user")
public class UserController {
    @Autowired
    private UserService userService;

    @Reference(check = false)
    private DubboUserService dubboUserService;

    @Autowired
    private JedisCluster jedisCluster;

    @RequestMapping("/{module}")
    public String module(@PathVariable String module){
        return module;
    }

    @RequestMapping("/testHttpClient")
    @ResponseBody
    public List<User> testHttpClient(){
        return dubboUserService.findAll();
    }

    @PostMapping("/doRegister")
    @ResponseBody
    public SysResult doRegister(User user){
        dubboUserService.saveUser(user);
        return SysResult.success();
    }

    @PostMapping("/doLogin")
    @ResponseBody
    public SysResult doLogin(User user, HttpServletResponse response){
        String uuid = dubboUserService.login(user);
        if(StringUtils.isEmpty(uuid)){
            return SysResult.fail();
        }
        Cookie cookie = new Cookie("JT_TICKET", uuid);
        cookie.setMaxAge(30*24*60*60);
        cookie.setPath("/");
        cookie.setDomain("jt.com");
        response.addCookie(cookie);
        return SysResult.success();
    }

    @RequestMapping("/logout")
    public String logout(HttpServletRequest request,HttpServletResponse response){
        Cookie[] cookies = request.getCookies();
        if (cookies!=null&&cookies.length>0){
            for (Cookie cookie:cookies){
                if (cookie.getName().equals("JT_TICKET")){
                    String ticket = cookie.getValue();
                    jedisCluster.del(ticket);
                    cookie.setMaxAge(0);
                    cookie.setPath("/");
                    cookie.setDomain("jt.com");
                    response.addCookie(cookie);
                }
            }
        }
        return "redirect:/";
    }

}
